import { showSpeaker } from './speak';
import type { playerData } from './userBox';
import { UserBox } from './userBox';

const adminScreen = UiScreen.getAllScreen().find(
    (e) => e.name === 'adminScreen'
);

function sendServer(type: string, data: string | number | object) {
    remoteChannel.sendServerEvent({ type, data });
}
// admin 后台按键

async function button(target: UiNode) {
    const uiScale = UiScale.create();
    target.uiScale = uiScale;
    uiScale.scale = 0.9;
    await sleep(100);
    uiScale.scale = 1;
}

const Kick = adminScreen?.findChildByName<UiBox>('Kick');
const DeleteBlack = adminScreen?.findChildByName<UiBox>('DeleteBlack');
const Black = adminScreen?.findChildByName<UiBox>('Black');
const giveMai = adminScreen?.findChildByName<UiBox>('给麦克风');
const awayMai = adminScreen?.findChildByName<UiBox>('收麦克风');
const onStage = adminScreen?.findChildByName<UiBox>('上舞台');
const awayStage = adminScreen?.findChildByName<UiBox>('下舞台');
const activity_button = adminScreen?.findChildByName<UiBox>('流程操作');

const gotoBackend_button = adminScreen?.findChildByName<UiBox>('前往后台');
const chatMuted = adminScreen?.findChildByName<UiBox>('发言处罚');
const PeopleAdmin = adminScreen?.findChildByName<UiBox>('人员管理');

const add_camera_targets = adminScreen?.findChildByName<UiBox>('镜头追踪');
const delete_camera_targets =
    adminScreen?.findChildByName<UiBox>('删除镜头追踪');

const server_button = adminScreen?.findChildByName<UiBox>('服务器');
const sound_button = adminScreen?.findChildByName<UiBox>('音效');
const bgm_button = adminScreen?.findChildByName<UiBox>('背景音乐');
if (
    !Kick ||
    !DeleteBlack ||
    !Black ||
    !giveMai ||
    !awayMai ||
    !onStage ||
    !awayStage ||
    !activity_button ||
    !gotoBackend_button ||
    !add_camera_targets ||
    !delete_camera_targets ||
    !server_button ||
    !sound_button ||
    !bgm_button ||
    !chatMuted ||
    !PeopleAdmin
) {
    throw new Error('不存在 ');
}

input.uiEvents.on('pointerup', ({ target }) => {
    if (target.name === '前往后台') {
        button(target);
        sendServer('前往后台', 1);
    }
    if (target.name === '发言处罚') {
        button(target);
        sendServer('发言处罚', 1);
    }
    if (target.name === '人员管理') {
        button(target);

        sendServer('人员管理', 1);
    }
});

// 假设 UiBox、Coord2 等类型已定义
interface BoxConfig {
    button: UiBox;
    title: string;
    screen: string;
    data: Array<playerData>;
    handle: (
        userId: string,
        name: string,
        avatar: string,
        target: UiNode
    ) => void;
    // ... 其他字段
}
// 限定 key 为字面量类型（比如 'kick' 等固定值，根据实际 key 改）
type BoxKeys = string; // 'kick' | 'otherkey'
const USER_BOXES_DATA: Record<BoxKeys, BoxConfig> = {
    kick: {
        button: Kick,
        title: '踢人',
        screen: 'adminScreen',

        data: [],
        handle: (
            userId: string,
            name: string,
            avatar: string,
            target: UiNode
        ) => {
            button(target);
            sendServer('Kick', userId);
        },
    },
    black: {
        button: Black,
        title: '拉黑',
        screen: 'adminScreen',

        data: [],
        handle: (
            userId: string,
            name: string,
            avatar: string,
            target: UiNode
        ) => {
            button(target);
            console.log('尝试拉黑', userId);
            sendServer('Black', userId);
        },
    },
    DeleteBlack: {
        button: DeleteBlack,
        title: '解除拉黑',
        screen: 'adminScreen',

        data: [],
        handle: (
            userId: string,
            name: string,
            avatar: string,
            target: UiNode
        ) => {
            button(target);
            console.log('(client)解除拉黑', userId);
            sendServer('DeleteBlack', userId);
        },
    },
    giveMai: {
        button: giveMai,
        title: '给麦克风',
        screen: 'adminScreen',

        data: [],
        handle: (
            userId: string,
            name: string,
            avatar: string,
            target: UiNode
        ) => {
            button(target);
            // console.log('', userId);
            sendServer('giveMai', userId);
        },
    },
    awayMai: {
        button: awayMai,
        title: '收麦克风',
        screen: 'adminScreen',
        data: [],
        handle: (
            userId: string,
            name: string,
            avatar: string,
            target: UiNode
        ) => {
            button(target);
            // console.log('', userId);
            sendServer('awayMai', userId);
        },
    },
    onStage: {
        button: onStage,
        title: '上舞台',
        screen: 'adminScreen',
        data: [],
        handle: (
            userId: string,
            name: string,
            avatar: string,
            target: UiNode
        ) => {
            button(target);
            // console.log('', userId);
            sendServer('onStage', userId);
        },
    },
    awayStage: {
        button: awayStage,
        title: '下舞台',
        screen: 'adminScreen',
        data: [],
        handle: (
            userId: string,
            name: string,
            avatar: string,
            target: UiNode
        ) => {
            button(target);
            // console.log('', userId);-
            sendServer('awayStage', userId);
        },
    },
    activity_button: {
        button: activity_button,
        title: '流程操作',
        screen: 'adminScreen',
        data: [],
        handle: (
            userId: string,
            name: string,
            avatar: string,
            target: UiNode
        ) => {
            button(target);
            // console.log('', userId);-
            sendServer('activity_button', name);
        },
    },
    add_camera_targets: {
        button: add_camera_targets,
        title: '镜头追踪',
        screen: 'adminScreen',
        data: [],
        handle: (
            userId: string,
            name: string,
            avatar: string,
            target: UiNode
        ) => {
            button(target);
            // console.log('', userId);-
            sendServer('add_camera_targets', userId);
        },
    },
    delete_camera_targets: {
        button: delete_camera_targets,
        title: '删除镜头追踪',
        screen: 'adminScreen',
        data: [],
        handle: (
            userId: string,
            name: string,
            avatar: string,
            target: UiNode
        ) => {
            button(target);
            // console.log('', userId);-
            sendServer('delete_camera_targets', userId);
        },
    },
    server_button: {
        button: server_button,
        title: '服务器传送',
        screen: 'adminScreen',
        data: [],
        handle: (
            userId: string,
            name: string,
            avatar: string,
            target: UiNode
        ) => {
            button(target);
            // console.log('', userId);-
            sendServer('server_button', userId);
        },
    },
    sound_button: {
        button: sound_button,
        title: '音效控制',
        screen: 'adminScreen',
        data: [],
        handle: (
            userId: string,
            name: string,
            avatar: string,
            target: UiNode
        ) => {
            button(target);
            // console.log('', userId);-
            sendServer('sound_button', userId);
        },
    },
    bgm_button: {
        button: bgm_button,
        title: '背景音乐控制',
        screen: 'adminScreen',
        data: [],
        handle: (
            userId: string,
            name: string,
            avatar: string,
            target: UiNode
        ) => {
            button(target);
            // console.log('', userId);-
            sendServer('bgm_button', userId);
        },
    },
};

const USER_BOXES: { [key: string]: UserBox } = {};

// 批量初始化
for (const [key, config] of Object.entries(USER_BOXES_DATA) as [
    BoxKeys,
    BoxConfig,
][]) {
    const target = USER_BOXES_DATA[key].button as UiBox;
    const position = Coord2.create({
        offset: Vec2.create({
            x: target?.position.offset.x,
            y: target?.position.offset.y - target?.size.offset.y - 10,
        }),
        scale: Vec2.create({
            x: target?.position.scale.x,
            y: target?.position.scale.y,
        }),
    });
    const anchor = Vec2.create({
        x: target?.anchor.x,
        y: target?.anchor.y,
    });
    USER_BOXES[key] = new UserBox(
        config.screen,
        Date.now(),
        config.title,
        position,
        anchor,
        config.data,
        config.handle
    );
    if (config && config.button) {
        config.button.events.on('pointerup', () => {
            // sendServer('Kick', )
            if (!USER_BOXES[key].box) {
                return;
            }

            button(config.button as UiNode);
            USER_BOXES[key].box.visible = !USER_BOXES[key].box?.visible;
        });
    }
}

/**弹幕 */
let barrageIndex = 0;
const MAX_BARRAGE_INDEX = 3;
const barrageUi = UiScreen.getAllScreen()
    .find((e) => e.name === 'screen')
    ?.findChildByName<UiBox>('barrages');
interface barrageData {
    content: string;
    color: {
        r: number;
        g: number;
        b: number;
    };
    image: string | undefined;
}
/**弹幕调用 */
async function barrage({ content, color, image }: barrageData) {
    const box = UiText.create();
    if (image) {
        const images = UiImage.create();
        images.parent = box;
        images.size.offset.x = 35;
        images.size.offset.y = 35;
        images.position.offset.x -= images.size.offset.x + 10;
        images.image = image;
    }
    box.anchor.x = 0;
    box.parent = barrageUi;
    box.textFontSize = 22;
    box.textFontFamily = UITextFontFamily.BoldRound;
    box.textColor.copy(Vec3.create(color));
    box.textContent = String(content); // 设置文本内容
    if (barrageUi) {
        box.position.scale.x = barrageUi?.size.scale.x + 0.4;
    }
    // console.log(box.position.offset.x)
    box.size.offset.x = 0;
    box.size.offset.y = 0;
    box.autoResize = 'XY';
    box.backgroundOpacity = 0.4;
    box.backgroundColor.copy(Vec3.create({ r: 0.5, g: 0.5, b: 0 }));
    box.visible = true;
    box.richText = true;
    box.position.offset.y = 40 * barrageIndex + 55;
    if (barrageIndex >= MAX_BARRAGE_INDEX) {
        barrageIndex = 0;
    } else {
        barrageIndex += 1;
    }

    for (
        let i = box.position.scale.x;
        i >= -1 * (content.length / 50);
        i -= 0.008
    ) {
        box.position.scale.x = i;
        await sleep(64);
    }
    box.parent = undefined;
}

if (barrageUi) {
    barrageUi.events.on('pointerdown', () => {
        input.lockPointer();
    });
}

remoteChannel.events.on('client', (args) => {
    const { type, data } = args;
    if (type === 'barrage') {
        barrage(args.data);
    }
    if (type === 'chat') {
        const { entity, message, type } = data;
        console.warn('收到', message);
        showSpeaker({
            name: entity.name,
            avatar: entity.avatar,
            userId: entity.id,
            text: message,
            type: type,
        });
    }

    if (type === 'online') {
        USER_BOXES.kick.updatePlayer(data);
        USER_BOXES.black.updatePlayer(data);
        USER_BOXES.onStage.updatePlayer(data);
        USER_BOXES.giveMai.updatePlayer(data);
        USER_BOXES.add_camera_targets.updatePlayer(data);
    }

    const allTypes = [
        'DeleteBlack',
        'awayMai',
        'awayStage',
        'activity_button',
        'server_button',
        'sound_button',
        'bgm_button',
    ];

    if (allTypes.includes(type)) {
        USER_BOXES[type].updatePlayer(data);
    }

    // ui显示
    if (type === 'showUI' || type === 'hideUI') {
        const { screen, ui_name } = data;
        const obj = UiScreen.getAllScreen()
            .find((obj) => obj.name === screen)
            ?.findChildByName(ui_name);
        if (obj) {
            obj.visible = type === 'showUI';
        }
    }
    if (type === 'showScreen' || type === 'hideScreen') {
        const obj = UiScreen.getAllScreen().find((obj) => obj.name === data);
        if (obj) {
            obj.visible = type === 'showScreen';
        }
    }

    if (type === 'updateUI') {
        const { userId, serverId, ping, online } = data;
        const mainScreen = UiScreen.getAllScreen().find(
            (obj) => obj.name === 'screen'
        );

        const userIdUI = mainScreen?.findChildByName<UiText>('userId');
        const serverIdUI = mainScreen?.findChildByName<UiText>('serverId');
        const pingUI = mainScreen?.findChildByName<UiText>('ping');
        const onlineUI = mainScreen?.findChildByName<UiText>('online');
        if (userIdUI && serverIdUI && pingUI && onlineUI) {
            userIdUI.textContent = `UserId: ${userId}`;
            serverIdUI.textContent = `ServerId: ${serverId}`;
            pingUI.textContent = `Ping: ${ping}ms`;
            onlineUI.textContent = `Online: ${online}`;
        }
    }
});
